package assistant

import (
	"context"
	"encoding/json"
	"github.com/felixrobcoding/go-common/asynq"
	queue "github.com/hibiken/asynq"
	"maya-service/config"
	"maya-service/event"
	modelEvent "maya-service/model/event"
)

var AsynqQueue = &asynqQueue{}

func init() {
	Register(AsynqQueue)
}

type asynqQueue struct {
	client *asynq.AsynqService
}

func (a *asynqQueue) Init() func() {
	conf := &asynq.Config{
		Host: "127.0.0.1:6379",
		Pwd:  "123456",
		Db:   0,
	}

	if len(config.Conf.DB) > 0 {
		for _, db := range config.Conf.DB {
			if !db.Enabled {
				continue
			}
			switch db.Type {
			case "mysql":
			case "postgres":
			case "redis":
				conf.Host = db.Addr
				conf.Pwd = db.Pwd
			default:

			}
		}
	}

	a.client = asynq.NewAsynq(conf)
	a.Subscribe()
	err := a.client.Start()
	if err != nil {
		panic(err)
	}
	return func() {}
}

func (a *asynqQueue) GetAsynqClient() *asynq.AsynqService {
	return a.client
}

func (a *asynqQueue) Subscribe() {
	a.GetAsynqClient().SubscribeConsumer("delivery_session", func(ctx context.Context, task *queue.Task) error {
		data := &modelEvent.DeliverySession{}
		_ = json.Unmarshal(task.Payload(), data)
		event.Publish(ctx, event.DeliverySession, data)
		return nil
	})

	a.GetAsynqClient().SubscribeConsumer("test", func(ctx context.Context, task *queue.Task) error {
		data := &modelEvent.DeliverySession{}
		_ = json.Unmarshal(task.Payload(), data)
		event.Publish(ctx, event.Test, data)
		return nil
	})
}
